<?php
declare(strict_types=1);

use Illuminate\Support\Str;

if (!function_exists('get_property')) {
    function get_property($obj, $property, $default = null)
    {
        if (!$obj) {
            return $default;
        }
        if (is_string($obj)) {
            $obj = json_decode($obj, true);
        }
        if (is_object($obj)) {
            return property_exists($obj, $property) || isset($obj->$property) ? $obj->$property : $default;
        }

        // 注意⚠：️ 当 $obj[$property] 的值为 NULL 时 isset 返回的是 false。
        // 也就是说，当 $obj 中存在 $property 但是值为 NULL 时，不会返回 NULL，而是返回 $default
        return $obj[$property] ?? $default;
    }
}

if (!function_exists('fen_to_yuan')) {
    /**
     * 金额分转元
     * 转化金额 100010分  ->   1000.10 元
     * @param $money
     * @return string
     */
    function fen_to_yuan($money)
    {
        if (empty($money)) {
            return 0;
        }
        $res = bcdiv((string)$money, '100', 2);
        return $money % 100 == 0 ? (int)$res : $res;
    }
}

/**
 * is_https
 */
if (!function_exists('is_https')) {
    function is_https(): bool
    {
        if (get_property($_SERVER, 'HTTPS', '') !== 'off'
            || get_property($_SERVER, 'HTTP_X_CLIENT_PROTO', '') === 'https'
            || get_property($_SERVER, 'HTTP_X_FORWARDED_PROTO', '') === 'https'
            || get_property($_SERVER, 'HTTP_FRONT_END_HTTPS', '') !== 'off') {
            return true;
        }

        return false;
    }
}

/**
 * 金额格式化
 */
if (!function_exists('amount_format')) {
    function amount_format($money): string
    {
        return number_format((float)$money, 2, ".", ",");
    }
}

if (!function_exists('use_time')) {
    function use_time()
    {
        $mtime = microtime();
        $time = explode(' ', $mtime);
        return $time[1] + $time[0];
    }
}

if (!function_exists('format_time')) {
    function format_time($time)
    {
        if (is_numeric($time)) {
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if ($time >= 31556926) {
                $value["years"] = floor($time / 31556926);
                $time = ($time % 31556926);
            }
            if ($time >= 86400) {
                $value["days"] = floor($time / 86400);
                $time = ($time % 86400);
            }
            if ($time >= 3600) {
                $value["hours"] = floor($time / 3600);
                $time = ($time % 3600);
            }
            if ($time >= 60) {
                $value["minutes"] = floor($time / 60);
                $time = ($time % 60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t = "";
            if (!empty($value['years'])) {
                $t .= $value["years"] . "年";
            }
            if (!empty($value["days"])) {
                $t .= $value['days'] . "天";
            }
            if (!empty($value["hours"])) {
                $t .= $value['hours'] . "小时";
            }
            if (!empty($value["minutes"])) {
                $t .= $value['minutes'] . "分";
            }
            $t .= $value["seconds"] . "秒";
            return $t;
        } else {
            return false;
        }
    }
}

if (!function_exists('take_time')) {
    function take_time($startTime)
    {
        return format_time(use_time() - $startTime);
    }
}

if (!function_exists('use_memory')) {
    function use_memory(): int
    {
        return memory_get_usage();
    }
}

if (!function_exists('format_memory')) {
    function format_memory($bytes): string
    {
        $units = [' B', ' KB', ' MB', ' GB', ' TB'];
        for ($i = 0; $bytes >= 1024 && $i < 4; $i++) $bytes /= 1024;
        return round($bytes, 2) . $units[$i];
    }
}

if (!function_exists('take_memory')) {
    function take_memory($startMemory): string
    {
        return format_memory(use_memory() - $startMemory);
    }
}

if (!function_exists('rand_str')) {
    /**
     * 取得随机代码,并上锁60秒
     * @param int $length
     * @param string $type
     * @param bool $isNumeric
     * @return string
     */
    function rand_str(int $length = 32, string $type = '', bool $isNumeric = false): string
    {
        if ($isNumeric) {
            $chars = "0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
                $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
        } else {
            $str = \Illuminate\Support\Str::lower(\Illuminate\Support\Str::random($length));
        }
        if ($type) {
            $key = 'randstr_' . $type . '_' . $str;
        } else {
            $key = 'randstr_' . $str;
        }
        if (\App\Library\Util\LockUtil::lock($key, 60)) {
            return rand_str($length, $type, $isNumeric);
        } else {
            return $str;
        }
    }
}

/**
 * build uri
 */
if (!function_exists('build_uri')) {
    function build_uri($length = 16, $type = '', $isNumeric = false): string
    {
        return date("ymd") . rand_str($length, $type, $isNumeric);
    }
}


/**
 * curl post
 * @param $url
 * @param array $data
 * @param array $header
 * @return bool|string
 * @throws Exception
 */
function http_post($url, $data = [], $header = [])
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    }
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $tmpInfo = curl_exec($curl);
    if (curl_errno($curl)) {
        throw new Exception('Errno' . curl_error($curl), curl_errno($curl));
    }
    curl_close($curl);
    return $tmpInfo;
}

